package com.acoreful.acf2admin.web.utils;

import javax.servlet.http.HttpServletRequest;

public class WebUtils {
	private final String REQUEST_SPLIT_CHAR=",";
	private final String ERROR_IP="";

	/**
	 * 获取客户端IP
	 * @param request
	 * @param remoteFirst	是否远程IP优先，对于面向移动端的用户来说，需要设置成true，以便阻止移动端利用head来伪造IP
	 * @return
	 */
	public String getIpAddr(final HttpServletRequest request,boolean remoteFirst){
		String remoteAddr="";
		if(remoteFirst){
			remoteAddr=request.getRemoteAddr();
			if(isEffective(remoteAddr)){
				return remoteAddr;
			}
		}
		try {
			remoteAddr=request.getHeader("X-Forwarded-For");
			//如果通过多级代理，X-Forwarded-For的值不止一个，而是一串用逗号分隔的IP值，此时取X-Forwarded-For的值中的第一个非unknown的有效IP地址
			if(isEffective(remoteAddr)&&remoteAddr.indexOf(REQUEST_SPLIT_CHAR)>-1){
				String[] array=remoteAddr.split(REQUEST_SPLIT_CHAR);
				for (String element : array) {
					if(isEffective(remoteAddr)){
						remoteAddr= element;
						break;
					}
				}
			}
			if(!isEffective(remoteAddr)){
				remoteAddr=request.getHeader("Proxy-Client-IP");
			}
			if(!isEffective(remoteAddr)){
				remoteAddr=request.getHeader("WL-Proxy-Client-IP");
			}
			if(!isEffective(remoteAddr)){
				remoteAddr=request.getHeader("X-Real-IP");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_IP;
		}
		return remoteAddr;
	}
	
	/**
	 * @param ip
	 * @return
	 */
	public boolean isEffective(String ip){
		if(ip==null){
			return false;
		}
		return !"unknown".equalsIgnoreCase(ip);
	}
}
